package com.kindnesslibrary.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.TextView;

import com.kindnesslibrary.R;
import com.kindnesslibrary.activity.adapter.XImageAdapter;
import com.kindnesslibrary.base.BaseActivity;
import com.kindnesslibrary.model.XImageModel;
import com.kindnesslibrary.util.AlbumHelper;
import com.kindnesslibrary.util.Contants;
import com.kindnesslibrary.util.ToastUtil;
import com.kindnesslibrary.ximage.XImage;
import com.kindnesslibrary.ximage.XImgSelConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图片选择
 */
public class XImageActivity extends BaseActivity {

    private TextView tv_ximage_choose_num;
    RecyclerView rv_ximage_data;
    private ArrayList<XImageModel> mXImageModels = new ArrayList<>();
    private XImageAdapter xImageAdapter; // 图片适配器，分为3列图片格局
    private AlbumHelper helper;// 图片集帮助类
    private final int imageShowColumn = 3; // 3列
    private int checkImages = 9; // 默认可选择9张图片

    @Override
    protected void initData(Bundle savedInstanceState) {
        helper = AlbumHelper.getInstance();
        tv_ximage_choose_num = (TextView) findViewById(R.id.tv_ximage_choose_num);
        xImageAdapter = new XImageAdapter(this, R.layout.item_ximage_layout, mXImageModels);
        rv_ximage_data = (RecyclerView) findViewById(R.id.rv_ximage_data);
        rv_ximage_data.setAdapter(xImageAdapter);
        rv_ximage_data.setHasFixedSize(true);
        rv_ximage_data.setLayoutManager(new GridLayoutManager(this, imageShowColumn));

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED) {
            getPhotos(); // 已经获取读权限则获取读取相片资源
        } else {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE}, Contants.ALBUM_CONTENT_DATA_CODE); // 请求读权限
        }
        checkImages = XImage.getConfig().maxNum;
        tv_ximage_choose_num.setText("0/" + checkImages);
    }

    @Override
    protected void initEvent() {
        findViewById(R.id.ll_ximage_back).setOnClickListener(v -> {
            finish();
        });
        // 右边确定按钮
        findViewById(R.id.tv_ximage_choose).setOnClickListener(v -> {
            ArrayList<String> paths = new ArrayList<String>();
            if (XImage.getConfig().selectImage.size() == 0) {
                ToastUtil.showToast("请选择图片");
                return;
            }
            paths.addAll(XImage.getConfig().selectImage);
            Intent intent = new Intent();
            intent.putExtra(Contants.ALBUM_LIST, paths);
            setResult(RESULT_OK, intent);
            finish();
        });
        // 预览按钮
        findViewById(R.id.tv_ximage_choose_preview).setOnClickListener(view -> {
            Intent intent = new Intent(XImageActivity.this, ImagePreviewActivity.class);
            intent.putExtra(Contants.ALBUM_LIST, mXImageModels);
            startActivityForResult(intent, Contants.PREVIEW_DATA_CODE);
        });
        // 点击适配器选项
        xImageAdapter.setOnViewItemClickListener(xImageModel -> {
            if (XImage.getConfig().selectImage.size() >= XImage.getConfig().maxNum &&
                    !XImage.getConfig().selectImage.contains(xImageModel.filePath)) {
                ToastUtil.showToast("最多只能选择 " + XImage.getConfig().maxNum + " 张哦");
                return;
            }
            if (!XImage.getConfig().selectImage.contains(xImageModel.filePath)) {
                XImage.getConfig().selectImage.add(xImageModel.filePath);
            } else {
                XImage.getConfig().selectImage.remove(xImageModel.filePath);
            }
            xImageAdapter.notifyItemChanged(xImageModel.position);
            tv_ximage_choose_num.setText(XImage.getConfig().selectImage.size() + "/" + checkImages);
        });
        rv_ximage_data.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                xImageAdapter.updateStatus(newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                        GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                        int firstVisibleItemPosition = gridLayoutManager.findFirstVisibleItemPosition();
                        int lastVisibleItemPosition = gridLayoutManager.findLastVisibleItemPosition();
                        handler.postDelayed(() -> {
                            if(xImageAdapter.getStatus() == RecyclerView.SCROLL_STATE_IDLE){
                                xImageAdapter.notifyItemRangeChanged(firstVisibleItemPosition, lastVisibleItemPosition);
                            }
                        }, 1000);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_ximage_layout;
    }

    @Override
    protected void handlerMessage(Message msg) {

    }

    /**
     * 获取相册
     */
    private void getPhotos() {
        startRunnable(() -> {
            ArrayList<Map<String, Object>> albumList = helper.getImagesBucketList();
            if (albumList != null)
                for (int i = 0; i < albumList.size(); i++) {
                    if (albumList.get(i) == null) {
                        albumList.remove(i--);
                    }
                }
            for (Map<String, Object> album : albumList) {
                if (album != null && album.size() > 0) {
                    List<Map<String, String>> contentParams = ((List<Map<String, String>>) album.get("imageList"));
                    for (Map<String, String> contentMap : contentParams) {
                        XImageModel xImageModel = new XImageModel();
                        xImageModel.isCheck = false;
                        xImageModel.thumbnailPath = contentMap.get("thumbnailPath");
                        xImageModel.filePath = contentMap.get("imagePath");
                        if (!TextUtils.isEmpty(xImageModel.filePath) && new File(xImageModel.filePath).exists()) {
                            mXImageModels.add(xImageModel);
                        }
                    }
                }
            }
            handler.post(() -> {
                xImageAdapter.notifyDataSetChanged();
            });
        });
    }

    /**
     * 打开图片选择器
     *
     * @param context     上下文
     * @param config      配置参数
     * @param requestCode 请求code
     */
    public static void open(Activity context, XImgSelConfig config, int requestCode) {
        XImage.setConfig(config);
        context.startActivityForResult(new Intent(context, XImageActivity.class), requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Contants.PREVIEW_DATA_CODE: {
                    Intent intent = new Intent();
                    intent.putExtra(Contants.ALBUM_LIST, XImage.getConfig().selectImage);
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            }
        }
    }

    /**
     * 6.0以上版本读权限处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Contants.ALBUM_CONTENT_DATA_CODE) {
            if (permissions.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getPhotos();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE}, Contants.ALBUM_CONTENT_DATA_CODE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        xImageAdapter.notifyDataSetChanged();
    }

    /**
     * 回收选择图片
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        XImage.getConfig().selectImage.clear();
        System.gc();
    }
}
